package com.boxedinsoftware.betamax.dial;



import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;


 public class OutgoingCallReceiver extends Activity {

	 protected SharedPreferences preferences;
	 String number;
	 String country;
	 AlertDialog alertDialog;
	 AccountsSQLHelper dh;
	 
	 
	 @Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			
			String full_number = this.getIntent().getDataString();
			String numberzor = full_number.substring(full_number.indexOf(":") + 1, full_number.length());
			if(numberzor.startsWith("00"))
			{
				number = numberzor.replaceFirst("00", "+");
			}
			else
				number = numberzor.replaceAll("%2B", "+");
			number = number.replaceAll( "-", "" );
            number = number.replace(")", "");
            number = number.replace("(", "");
            number = number.replaceAll(" ", "");
            number = number.replaceAll("[a-z,A-Z]", "");
            
            preferences = PreferenceManager.getDefaultSharedPreferences(this);
			boolean directCall = preferences.getBoolean("directDialer", false);
			String defPrefix = preferences.getString("defaultPrefix" , "");
			if(directCall == false && !number.startsWith("+") && defPrefix.length() > 0 )
				number = defPrefix + number;
            
			country = CountryCodes.searchFor(number);
			//Toast.makeText(this, number, Toast.LENGTH_LONG).show();
			
			if(directCall == true && !number.startsWith("+"))
			{
				
				choice3();
				
			}
			else
			{
			this.dh = new AccountsSQLHelper(OutgoingCallReceiver.this.getApplicationContext());
			refreshBalance();
			int choice = 0;
			
			Cursor c = this.dh.selectAllRules();
			while(c.moveToNext())
			{
				if(c.getString(1).equalsIgnoreCase(country) || c.getString(1).equalsIgnoreCase(number)){
					choice = c.getInt(2);
					break;
				}
				
				
			}
			
			
			
			if(choice == 0)
			{
			AlertDialog.Builder builder;
			

			Context mContext = OutgoingCallReceiver.this;
			LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
			View layout = inflater.inflate(R.layout.choose_action,
			                               (ViewGroup) findViewById(R.id.action_root));
			builder = new AlertDialog.Builder(mContext);
			builder.setView(layout);
			alertDialog = builder.create();
			alertDialog.show();
			
	        
	        TextView actionInfo = (TextView)layout.findViewById(R.id.textView1);
	        final CheckBox numberCheckbox = (CheckBox)layout.findViewById(R.id.checkBox1);
	        final CheckBox countryCheckbox = (CheckBox)layout.findViewById(R.id.checkBox2);
	        
	        actionInfo.setText("Complete action using");
	        numberCheckbox.setText("Use default for this number");
	        countryCheckbox.setText("Use default for " + country);
	        if(country.equalsIgnoreCase("Invalid Number"))
	        	countryCheckbox.setVisibility(8);
	        
	        numberCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener(){

				public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
					if(arg1 == true)
						countryCheckbox.setChecked(false);
					
				}
	        	
	        	
	        });
	        
	        
	        countryCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener(){

				public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
					if(arg1 == true)
						numberCheckbox.setChecked(false);
					
				}
	        	
	        	
	        });
	        
	        Button callback = (Button)layout.findViewById(R.id.button1);
	        Button call = (Button)layout.findViewById(R.id.button2);
	        Button dialer = (Button)layout.findViewById(R.id.button3);
	        
	        dialer.setOnClickListener(new OnClickListener(){

				public void onClick(View arg0) {
					if(numberCheckbox.isChecked())
						OutgoingCallReceiver.this.dh.insertRule(number, 3);
					else if(countryCheckbox.isChecked())
						OutgoingCallReceiver.this.dh.insertRule(country, 3);
					Uri uri = Uri.parse("tel:" + number);
                	//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
             	   Intent intent = new Intent(Intent.ACTION_CALL);
             	   intent.setData(uri);
             	   startActivity(intent);
             	   alertDialog.cancel();
             	   OutgoingCallReceiver.this.finish();
             	   
					
				}
	        	
	        	
	        });
	        
	        call.setOnClickListener(new OnClickListener(){

				public void onClick(View arg0) {
                	//Toast.makeText(getApplicationContext(), "call with accnumber", Toast.LENGTH_LONG).show();
					if(numberCheckbox.isChecked())
						OutgoingCallReceiver.this.dh.insertRule(number, 2);
					else if(countryCheckbox.isChecked())
						OutgoingCallReceiver.this.dh.insertRule(country, 2);
                	Intent i = new Intent(OutgoingCallReceiver.this, CallHandler.class);
                	i.putExtra("number", number);
                	i.putExtra("choice", 1);
                	i.putExtra("country", country);
                	OutgoingCallReceiver.this.startActivity(i);
                	alertDialog.cancel();
              	   OutgoingCallReceiver.this.finish();
					
				}
	        	
	        	
	        });
	        
	        callback.setOnClickListener(new OnClickListener(){

				public void onClick(View arg0) {
                	//Toast.makeText(getApplicationContext(), "callback", Toast.LENGTH_LONG).show();
					if(numberCheckbox.isChecked())
						OutgoingCallReceiver.this.dh.insertRule(number, 1);
					else if(countryCheckbox.isChecked())
						OutgoingCallReceiver.this.dh.insertRule(country, 1);
                	String sourceNumberString = preferences.getString("ownNumber","");
                	if(sourceNumberString.startsWith("+"))
                	{
                	String sourceNumberCountry = CountryCodes.searchFor(sourceNumberString);
                	Intent i = new Intent(OutgoingCallReceiver.this, CallHandler.class);
                 	i.putExtra("number", number);
                 	i.putExtra("choice", 2);
                 	i.putExtra("country", country);
                 	i.putExtra("sCountry", sourceNumberCountry);
                 	i.putExtra("sNumber", sourceNumberString);
                 	OutgoingCallReceiver.this.startActivity(i);
                 	alertDialog.cancel();
               	    OutgoingCallReceiver.this.finish();
                	}
                	else
                	{
                		Toast.makeText(getApplicationContext(), "Please check your preferences and set up your own number in International format", Toast.LENGTH_LONG).show();
                	}
				}
	        	
	        	
	        });
	       
			
			}
			else
			{
				
				if(choice == 1)
					choice1();
				else if (choice == 2)
					choice2();
				else if (choice == 3)
					choice3();
				
			}
			}
			
	 }
	 
	 public class refresh_balance extends AsyncTask<String, Void, String> {
	    	
	    	String[] params;
	    	
	    	@Override
	    	protected String doInBackground(String... params) {
	    		try{
	        		
	        		this.params = params;
					//Log.e("providerString", providerString);
					
					//Log.e("actualProvider", actualProvider);
					
				    HttpClient httpclient = new DefaultHttpClient();  
				    HttpGet httpget = new HttpGet("https://www."+params[1]+"/myaccount/getbalance.php?username="+params[2].trim()+"&password="+params[3].trim());
		            // Add your data  
		            
		      
		            // Execute HTTP Post Request  
		            HttpResponse response = httpclient.execute(httpget);  
		            
		            byte buffer[] = new byte[1024] ;
					InputStream is = response.getEntity().getContent() ;
					int numBytes = is.read(buffer) ;
					is.close();
					
					 String entityContents = new String(buffer,0,numBytes) ;
				    
						

						
			            
					 return entityContents;   
					}      
		         catch (ClientProtocolException e) { 
		        	Log.e("Betamax" , e.getMessage());
		        	return "error"; 
		        } catch (IOException e) {  
		        	Log.e("Betamax" , e.getMessage());
		        	return "error"; 
		        }
		        
	    	
	    	
	    	
	 }
	    	
	    	
	    	
	    	@Override
	    	protected void onPostExecute(String result) {
	    	
	    		if(result.equalsIgnoreCase("error")){
	    			Toast.makeText(OutgoingCallReceiver.this, "Something went wrong. Please check your internet connection", Toast.LENGTH_LONG).show();
	    		}
	    		else{
	    		params[4] = result;
	    		try{
	    		OutgoingCallReceiver.this.dh.update( Double.parseDouble(params[4]),Integer.parseInt(params[0]));}
	    		catch(Exception e){OutgoingCallReceiver.this.dh.update( -1.0,Integer.parseInt(params[0]));}
	    		}
	    	}
	    	
	 }
	 
	 public void refreshBalance(){
	     
	     Cursor cursor = this.dh.selectAllForBalance();
	        while (cursor.moveToNext()) {
	            int ID = cursor.getInt(0);
	            String provider = cursor.getString(1);
	            String username = cursor.getString(2);
	            String password = cursor.getString(3);
	            String[] params = {"" + ID , provider, username, password , ""};
	            new refresh_balance().execute(params);
	          }

	    }
	 
	 
	 @Override
	 public void onDestroy(){
		 super.onDestroy();
		 //this.dh.stop();
		 
	 }
	 
	 public void choice1(){
		 String sourceNumberString = preferences.getString("ownNumber","");
     	if(sourceNumberString.startsWith("+"))
     	{
     	String sourceNumberCountry = CountryCodes.searchFor(sourceNumberString);
     	Intent i = new Intent(OutgoingCallReceiver.this, CallHandler.class);
      	i.putExtra("number", number);
      	i.putExtra("choice", 2);
      	i.putExtra("country", country);
      	i.putExtra("sCountry", sourceNumberCountry);
      	i.putExtra("sNumber", sourceNumberString);
      	OutgoingCallReceiver.this.startActivity(i);
    	OutgoingCallReceiver.this.finish();
	 }
     	else
     	{
     		Toast.makeText(getApplicationContext(), "Please check your preferences and set up your own number in International format", Toast.LENGTH_LONG).show();
     	}
     	
	 }
	 
	 public void choice2(){
		 
		Intent i = new Intent(OutgoingCallReceiver.this, CallHandler.class);
     	i.putExtra("number", number);
     	i.putExtra("choice", 1);
     	i.putExtra("country", country);
     	OutgoingCallReceiver.this.startActivity(i);
   	   OutgoingCallReceiver.this.finish();
			
		
		 
	 }

	 public void choice3(){
	 
		 Uri uri = Uri.parse("tel:" + number);
     	//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
  	   Intent intent = new Intent(Intent.ACTION_CALL);
  	   intent.setData(uri);
  	   startActivity(intent);
  	   OutgoingCallReceiver.this.finish();
		 
	 }
	 
	
 }
 